﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Note_CHUSHI
{

    public partial class NoteEditorForm : Form
    {
        private Note currentNote;
        //临时图片存储路径
        private string tempImagePath = Path.Combine(Path.GetTempPath(), "NoteImages");
        private TextBox titleTextBox;//标题文本框
        private RichTextBox contentRichTextBox;//内容富文本框，RTF格式
        private ContextMenuStrip textContextMenu;//右键上下文菜单

        public NoteEditorForm(Note note)
        {
            currentNote = note;
            InitializeEditor();
            LoadNoteContent();
        }

        //编辑器页面
        private void InitializeEditor()
        {
            this.Text = $"{currentNote.Title} - 笔记编辑器";
            this.Size = new Size(1000, 700);
            this.StartPosition = FormStartPosition.CenterScreen;

            var mainPanel = new Panel { Dock = DockStyle.Fill };

            // 工具栏 (移除了剪切、复制、粘贴按钮)
            var toolStrip = new ToolStrip { Dock = DockStyle.Top };
            toolStrip.Items.Add(new ToolStripButton("保存", null, SaveNote_Click));
            toolStrip.Items.Add(new ToolStripButton("另存为", null, SaveAs_Click));
            toolStrip.Items.Add(new ToolStripSeparator());
            toolStrip.Items.Add(new ToolStripButton("撤销", null, Undo_Click));
            toolStrip.Items.Add(new ToolStripSeparator());
            toolStrip.Items.Add(new ToolStripButton("字体", null, Font_Click));
            toolStrip.Items.Add(new ToolStripButton("插入图片", null, InsertImage_Click));
            toolStrip.Items.Add(new ToolStripButton("插入日期", null, InsertDate_Click));

            titleTextBox = new TextBox
            {
                Dock = DockStyle.Top,
                Text = currentNote.Title,
                Font = new Font("微软雅黑", 12, FontStyle.Bold)
            };
            titleTextBox.TextChanged += Title_TextChanged;

            contentRichTextBox = new RichTextBox
            {
                Dock = DockStyle.Fill,
                AllowDrop = true,
                ContextMenuStrip = CreateTextContextMenu()
            };

            //绑定拖放
            contentRichTextBox.DragEnter += RichTextBox_DragEnter;
            contentRichTextBox.DragDrop += RichTextBox_DragDrop;
            contentRichTextBox.MouseUp += ContentRichTextBox_MouseUp;

            //状态栏
            var statusStrip = new StatusStrip { Dock = DockStyle.Bottom };
            statusStrip.Items.Add(new ToolStripStatusLabel("就绪…"));

            //控件添加到主面板
            mainPanel.Controls.Add(contentRichTextBox);
            mainPanel.Controls.Add(titleTextBox);
            this.Controls.AddRange(new Control[] { mainPanel, toolStrip, statusStrip });

            //创建临时图片目录
            Directory.CreateDirectory(tempImagePath);
        }

        //创建文本右键上下文菜单
        private ContextMenuStrip CreateTextContextMenu()
        {
            textContextMenu = new ContextMenuStrip();

            // 剪切菜单项
            var cutItem = new ToolStripMenuItem("剪切");
            cutItem.Click += (sender, e) => contentRichTextBox.Cut();
            textContextMenu.Items.Add(cutItem);

            // 复制菜单项
            var copyItem = new ToolStripMenuItem("复制");
            copyItem.Click += (sender, e) => contentRichTextBox.Copy();
            textContextMenu.Items.Add(copyItem);

            // 粘贴菜单项
            var pasteItem = new ToolStripMenuItem("粘贴");
            pasteItem.Click += (sender, e) => contentRichTextBox.Paste();
            textContextMenu.Items.Add(pasteItem);

            // 分隔线
            textContextMenu.Items.Add(new ToolStripSeparator());

            // 字体菜单项
            var fontItem = new ToolStripMenuItem("设置字体");
            fontItem.Click += (sender, e) =>
            {
                using (var fontDialog = new FontDialog())
                {
                    if (fontDialog.ShowDialog() == DialogResult.OK)
                    {
                        contentRichTextBox.SelectionFont = fontDialog.Font;
                    }
                }
            };
            textContextMenu.Items.Add(fontItem);

            return textContextMenu;
        }

        //鼠标抬起事件，用于更新右键菜单状态
        private void ContentRichTextBox_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                // 检查是否有选中文本
                bool hasSelection = contentRichTextBox.SelectionLength > 0;

                // 设置菜单项可用状态
                textContextMenu.Items[0].Enabled = hasSelection; // 剪切
                textContextMenu.Items[1].Enabled = hasSelection; // 复制
                textContextMenu.Items[3].Enabled = hasSelection; // 设置字体

                // 检查剪贴板是否有内容可粘贴
                textContextMenu.Items[2].Enabled = Clipboard.ContainsText();
            }
        }

        //加载笔记内容到编辑器
        private void LoadNoteContent()
        {
            try
            {
                if (!string.IsNullOrEmpty(currentNote.FilePath) && File.Exists(currentNote.FilePath))
                {
                    string extension = Path.GetExtension(currentNote.FilePath).ToLower();
                    if (extension == ".txt")
                    {
                        contentRichTextBox.Text = File.ReadAllText(currentNote.FilePath, Encoding.UTF8);
                    }
                    else if (extension == ".docx")
                    {
                        contentRichTextBox.Text = Note.LoadWordContent(currentNote.FilePath);
                    }
                    else if (extension == ".rtf")
                    {
                        contentRichTextBox.Rtf = File.ReadAllText(currentNote.FilePath);
                    }
                    else
                    {
                        throw new NotSupportedException("不支持的文件格式");
                    }
                }
                else if (!string.IsNullOrEmpty(currentNote.Content))
                {
                    contentRichTextBox.Text = currentNote.Content;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载笔记内容失败：{ex.Message}");
            }
        }

        //标题文本变化事件处理
        private void Title_TextChanged(object sender, EventArgs e)
        {
            currentNote.Title = titleTextBox.Text;
            this.Text = $"{currentNote.Title} - 笔记编辑器";
        }

        //拖放图片进入事件处理
        private void RichTextBox_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
        }

        //拖放完成
        private void RichTextBox_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                foreach (string file in files)
                {
                    string ext = Path.GetExtension(file).ToLower();
                    if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".gif")
                    {
                        InsertImageToContent(file);
                    }
                }
            }
        }

        //保存按钮
        private void SaveNote_Click(object sender, EventArgs e)
        {
            SaveNote();
        }

        //另存为按钮
        private void SaveAs_Click(object sender, EventArgs e)
        {
            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "RTF 文件|*.rtf|TXT 文件|*.txt|Word 文件|*.docx";
                saveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    currentNote.SetFilePath(saveDialog.FileName);

                    string extension = Path.GetExtension(saveDialog.FileName).ToLower();
                    if (extension == ".txt")
                    {
                        currentNote.Content = contentRichTextBox.Text; // 保存为纯文本
                    }
                    else if (extension == ".docx")
                    {
                        currentNote.Content = contentRichTextBox.Text; // 保存为 Word 文档
                    }
                    else if (extension == ".rtf")
                    {
                        currentNote.Content = contentRichTextBox.Rtf; // 保存为 RTF 格式
                    }

                    SaveNote();
                }
            }
        }

        //保存笔记
        private void SaveNote()
        {
            try
            {
                if (Path.GetExtension(currentNote.FilePath).ToLower() == ".txt")
                {
                    currentNote.Content = contentRichTextBox.Text; // 保存为纯文本
                }
                else if (Path.GetExtension(currentNote.FilePath).ToLower() == ".docx")
                {
                    currentNote.Content = contentRichTextBox.Text; // 保存为 Word 文档
                }
                else if (Path.GetExtension(currentNote.FilePath).ToLower() == ".rtf")
                {
                    currentNote.Content = contentRichTextBox.Rtf; // 保存为 RTF 格式
                }

                currentNote.Save();
                this.Text = $"{currentNote.Title} - 已保存";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存笔记失败：{ex.Message}");
            }
        }

        //窗体关闭前事件处理
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (contentRichTextBox.Modified)
            {
                var result = MessageBox.Show("笔记有未保存的更改，是否保存?", "提示",
                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    SaveNote();
                }
                else if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                    //加加加
                    return;
                }
            }

            base.OnFormClosing(e);
        }

        //撤销按钮
        private void Undo_Click(object sender, EventArgs e)
        {
            if (contentRichTextBox.CanUndo)
            {
                contentRichTextBox.Undo();
            }
        }

        //设置字体
        private void Font_Click(object sender, EventArgs e)
        {
            using (var fontDialog = new FontDialog())
            {
                if (fontDialog.ShowDialog() == DialogResult.OK)
                {
                    contentRichTextBox.SelectionFont = fontDialog.Font;
                }
            }
        }

        //插入图片按钮
        private void InsertImage_Click(object sender, EventArgs e)
        {
            using (var openDialog = new OpenFileDialog())
            {
                openDialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp;*.gif";
                if (openDialog.ShowDialog() == DialogResult.OK)
                {
                    InsertImageToContent(openDialog.FileName);
                }
            }
        }

        //插入图片实际实现
        private void InsertImageToContent(string imagePath)
        {
            try
            {
                var tempFile = Path.Combine(tempImagePath, Path.GetFileName(imagePath));
                File.Copy(imagePath, tempFile, true);
                Clipboard.SetImage(Image.FromFile(tempFile));
                contentRichTextBox.Paste();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"插入图片失败：{ex.Message}");
            }
        }

        //插入日期
        private void InsertDate_Click(object sender, EventArgs e)
        {
            contentRichTextBox.SelectedText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
    }

}